<!--
  * 数据源表单弹窗
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2024-01-01 00:00:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑数据源' : '新增数据源'"
    :width="800"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="submitLoading"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="数据源名称" name="name">
            <a-input v-model:value="form.name" placeholder="请输入数据源名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="数据库类型" name="type">
            <SmartEnumSelect
              v-model:value="form.type"
              enumName="DATABASE_TYPE_ENUM"
              placeholder="请选择数据库类型"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="主机地址" name="host">
            <a-input v-model:value="form.host" placeholder="请输入主机地址" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="端口号" name="port">
            <a-input-number
              v-model:value="form.port"
              placeholder="请输入端口号"
              :min="1"
              :max="65535"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="数据库名" name="databaseName">
            <a-input v-model:value="form.databaseName" placeholder="请输入数据库名" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="用户名" name="username">
            <a-input v-model:value="form.username" placeholder="请输入用户名" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="密码" name="password">
            <a-input-password
              v-model:value="form.password"
              placeholder="请输入密码"
              :disabled="isEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="连接池大小" name="connectionPoolSize">
            <a-input-number
              v-model:value="form.connectionPoolSize"
              placeholder="请输入连接池大小"
              :min="1"
              :max="100"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="连接超时时间" name="timeout">
            <a-input-number
              v-model:value="form.timeout"
              placeholder="请输入连接超时时间(秒)"
              :min="1"
              :max="300"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <SmartEnumSelect
              v-model:value="form.status"
              enumName="DATASOURCE_STATUS_ENUM"
              placeholder="请选择状态"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="备注" name="remark">
        <a-textarea
          v-model:value="form.remark"
          placeholder="请输入备注"
          :rows="3"
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button @click="handleTestConnection" :loading="testLoading">
          测试连接
        </a-button>
        <a-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { datasourceApi } from '/@/api/business/datasource/datasource-api';
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
  });

  const emit = defineEmits(['update:visible', 'success']);

  // 表单引用
  const formRef = ref();

  // 加载状态
  const submitLoading = ref(false);
  const testLoading = ref(false);

  // 表单数据
  const form = reactive({
    id: undefined,
    name: '',
    type: undefined,
    host: '',
    port: undefined,
    databaseName: '',
    username: '',
    password: '',
    connectionPoolSize: 10,
    timeout: 30,
    status: 1,
    remark: '',
  });

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入数据源名称' }],
    type: [{ required: true, message: '请选择数据库类型' }],
    host: [{ required: true, message: '请输入主机地址' }],
    port: [{ required: true, message: '请输入端口号' }],
    databaseName: [{ required: true, message: '请输入数据库名' }],
    username: [{ required: true, message: '请输入用户名' }],
    password: [{ required: true, message: '请输入密码' }],
    connectionPoolSize: [{ required: true, message: '请输入连接池大小' }],
    timeout: [{ required: true, message: '请输入连接超时时间' }],
    status: [{ required: true, message: '请选择状态' }],
  };

  // 是否为编辑模式
  const isEdit = computed(() => !!props.formData.id);

  // 监听表单数据变化
  watch(
    () => props.formData,
    (newVal) => {
      if (newVal && Object.keys(newVal).length > 0) {
        Object.assign(form, newVal);
      } else {
        resetForm();
      }
    },
    { immediate: true, deep: true }
  );

  // 重置表单
  const resetForm = () => {
    Object.assign(form, {
      id: undefined,
      name: '',
      type: undefined,
      host: '',
      port: undefined,
      databaseName: '',
      username: '',
      password: '',
      connectionPoolSize: 10,
      timeout: 30,
      status: 1,
      remark: '',
    });
    formRef.value?.resetFields();
  };

  // 测试连接
  const handleTestConnection = async () => {
    try {
      await formRef.value.validate();
      testLoading.value = true;
      const res = await datasourceApi.testConnection(form);
      message.success(res.data);
    } catch (error) {
      if (error.data) {
        message.error(error.data.msg || '连接测试失败');
      } else {
        message.error('连接测试失败');
      }
    } finally {
      testLoading.value = false;
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      await formRef.value.validate();
      submitLoading.value = true;

      if (isEdit.value) {
        await datasourceApi.update(form);
        message.success('更新成功');
      } else {
        await datasourceApi.create(form);
        message.success('创建成功');
      }

      emit('success');
    } catch (error) {
      if (error.data) {
        message.error(error.data.msg || '操作失败');
      } else {
        message.error('操作失败');
      }
    } finally {
      submitLoading.value = false;
    }
  };

  // 取消
  const handleCancel = () => {
    emit('update:visible', false);
    resetForm();
  };
</script> 